//$URL: http://dasding.googlecode.com/svn/trunk/data/dao/mongoDB/src/main/java/de/piratech/dasding/data/database/mongo/UserDataImpl.java $
//$Id: UserDataImpl.java 136 2013-05-10 22:02:55Z amuthmann@googlemail.com $
/*
 * Copyright 2012 Piratech.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package de.piratech.dasding.data.database.mongo;

import java.util.List;

import net.vz.mongodb.jackson.DBCursor;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.mongodb.DB;

import de.piratech.dasding.data.Action;
import de.piratech.dasding.data.ActionCategory;
import de.piratech.dasding.data.Event;
import de.piratech.dasding.data.EventCategory;
import de.piratech.dasding.data.User;
import de.piratech.dasding.data.database.DatabaseException;
import de.piratech.dasding.data.database.UserData;
import de.piratech.dasding.data.database.mongo.data.MongoActionCategory;
import de.piratech.dasding.data.database.mongo.data.MongoEventCategory;
import de.piratech.dasding.data.database.mongo.data.MongoUser;

/**
 */
public class UserDataImpl extends AbstractMongoDB<MongoUser, User> implements
    UserData {

  private static final Logger LOG = LoggerFactory.getLogger(UserDataImpl.class);

  public UserDataImpl(DB pDB) {
    super(pDB, MongoUser.class, COLLECTIONS.USER_COLLECTION);
  }

  @Override
  public User createUser(User pUser) throws DatabaseException {
    LOG.debug("createUser({})", pUser);
    User user;

    // ensure the user's login is unique
    try {
      user = getUserByName(pUser.getName());
    } catch (DatabaseException e) {
      return getDBCollection().insert(new MongoUser(pUser)).getSavedObject()
          .getDataObject();
    }
    if (user != null) {
      throw new DatabaseException("Username is not unique");
    }
    return getDBCollection().insert(new MongoUser(pUser)).getSavedObject()
        .getDataObject();
  }

  @Override
  public void deleteUser(User pUser) throws DatabaseException {
    List<Action> actions = new ActionDataImpl(db).findActionsByContact(pUser);
    List<Event> events = new EventDataImpl(db).findByCreator(pUser);
    List<ActionCategory> actionCategories = new ActionCategoryDataImpl(db)
        .findByCreated(pUser);
    List<EventCategory> eventCategories = new EventCategoryDataImpl(db)
        .findByCreated(pUser);

    if (actions != null && actions.size() > 0)
      throw new DatabaseException("user has related actions");
    if (events != null && events.size() > 0)
      throw new DatabaseException("user has related events");
    if (actionCategories != null && actionCategories.size() > 0)
      throw new DatabaseException("user has related action categories");
    if (eventCategories != null && eventCategories.size() > 0)
      throw new DatabaseException("user has related event categories");

    // TODO: remove user as action participant
    getDBCollection().removeById(pUser.getId());
  }

  @Override
  public void updateUser(User pUser) {
    LOG.debug("updateUser({})", pUser);
    getDBCollection().updateById(pUser.getId(), new MongoUser(pUser));
  }

  @Override
  public User getUserByName(String pName) throws DatabaseException {
    LOG.debug("getUser({})", pName);
    DBCursor<MongoUser> cursor = getDBCollection().find().is("name", pName);
    if (cursor.hasNext()) {
      return cursor.next().getDataObject();
    } else {
      throw new DatabaseException("user does not exit");
    }
  }

  public User getUserById(String pName) {
    LOG.debug("getUser({})", pName);
    return getDBCollection().findOneById(pName).getDataObject();
  }

  @Override
  public List<User> getUsers() throws DatabaseException {
    List<MongoUser> array = getDBCollection().find().toArray();
    List<User> list = getDataObjectList(array);
    return list;
  }

  public List<User> findUsersByActionCategory(ActionCategory actionCategory)
      throws DatabaseException {
    List<MongoUser> array = findByObjectRefInArray("interests",
        actionCategory.getId(), MongoActionCategory.class);
    List<User> users = getDataObjectList(array);
    return users;
  }

  public List<User> findUsersByEventCategory(EventCategory eventCategory)
      throws DatabaseException {
    List<MongoUser> array = findByObjectRefInArray("interestedIn",
        eventCategory.getId(), MongoEventCategory.class);
    List<User> users = getDataObjectList(array);
    return users;
  }
}
